﻿@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>明细报损维修管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/css/layui.min.css">
    <style>
        .layui-table-view {
            margin: 0;
        }

        .action-buttons {
            margin-bottom: 10px;
        }

        .search-form {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .detail-image {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
        }

        .user-role-info {
            background: #e8f4ff;
            padding: 8px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #1890ff;
        }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-row">
            <div class="layui-col-md12">
                <!-- 用户角色信息显示 -->
                <div class="user-role-info">
                    <i class="layui-icon layui-icon-user"></i>
                    当前用户权限:
                    <span id="currentUserRole">
                        @if (ViewBag.IsAdmin)
                        {
                            <span class="layui-badge layui-bg-red">管理员</span>
                        }
                        else
                        {
                            <span class="layui-badge layui-bg-blue">普通员工</span>
                        }
                    </span>
                </div>

                <!-- 搜索区域 -->
                <div class="search-form">
                    <form class="layui-form" id="searchForm" lay-filter="searchForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">资产名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="assetName" autocomplete="off" class="layui-input" placeholder="请输入资产名称">
                                </div>
                            </div>
                            @if (ViewBag.IsAdmin)
                            {
                                <div class="layui-inline">
                                    <label class="layui-form-label">申请人</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="empolyName" autocomplete="off" class="layui-input" placeholder="请输入申请人">
                                    </div>
                                </div>
                            }
                            <div class="layui-inline">
                                <label class="layui-form-label">维修状态</label>
                                <div class="layui-input-inline">
                                    <select name="recordState">
                                        <option value="">全部状态</option>
                                        <option value="0">申报中</option>
                                        <option value="1">已处理</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-normal" id="searchBtn">
                                    <i class="layui-icon">&#xe615;</i>搜索
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    @if (!ViewBag.IsAdmin)
                    {
                        <button class="layui-btn layui-btn-normal" id="applyRepairBtn">
                            <i class="layui-icon">&#xe654;</i>申请报修
                        </button>
                    }
                </div>

                <!-- 表格 -->
                <table class="layui-hide" id="damageRepairTable" lay-filter="damageRepairTable"></table>
            </div>
        </div>
    </div>

    <!-- 申请报修表单（普通员工） -->
    <div id="applyRepairForm" style="display: none; padding: 20px;">
        <form class="layui-form" id="repairApplyForm">
            <div class="layui-form-item">
                <label class="layui-form-label">明细编号</label>
                <div class="layui-input-block">
                    <select name="assetDetailID" lay-verify="required" lay-search>
                        <option value="">请选择资产</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">损坏日期</label>
                <div class="layui-input-block">
                    <input type="text" name="damageDate" id="damageDate" lay-verify="required" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">损坏原因</label>
                <div class="layui-input-block">
                    <input type="text" name="damageCauses" lay-verify="required" placeholder="请输入损坏原因" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">问题描述</label>
                <div class="layui-input-block">
                    <textarea name="problemDescription" lay-verify="required" placeholder="请详细描述问题" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">图片描述</label>
                <div class="layui-input-block">
                    <input type="file" name="problemImage" class="layui-upload-file">
                    <div class="layui-upload-list">
                        <img class="layui-upload-img" id="previewImage" style="display:none; max-width: 200px; max-height: 200px;">
                        <div id="uploadText">未选择任何文件</div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="repairSubmit">立即报修</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 查看详情弹窗 -->
    <div id="detailForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="detailForm">
            <div class="layui-form-item">
                <label class="layui-form-label">资产名称：</label>
                <div class="layui-input-block">
                    <span id="detailAssetName"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">图片描述：</label>
                <div class="layui-input-block">
                    <img id="detailImage" class="detail-image" src="" onerror="this.style.display='none'">
                    <div id="noImageText" style="color: #999;">暂无图片</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">损坏原因：</label>
                <div class="layui-input-block">
                    <span id="detailDamageCauses"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">问题描述：</label>
                <div class="layui-input-block">
                    <span id="detailProblemDescription"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">申报人：</label>
                <div class="layui-input-block">
                    <span id="detailEmpolyName"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">申报时间：</label>
                <div class="layui-input-block">
                    <span id="detailDamageDate"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">维修人：</label>
                <div class="layui-input-block">
                    <span id="detailRepairman"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">维修日期：</label>
                <div class="layui-input-block">
                    <span id="detailRepairDates"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">维修状态：</label>
                <div class="layui-input-block">
                    <span id="detailRecordState"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注：</label>
                <div class="layui-input-block">
                    <span id="detailRemark"></span>
                </div>
            </div>
        </form>
    </div>

    <!-- 处理维修表单（管理员） -->
    <div id="processRepairForm" style="display: none; padding: 20px;">
        <form class="layui-form" id="repairProcessForm">
            <input type="hidden" name="damageRecordID">
            <div class="layui-form-item">
                <label class="layui-form-label">维修人</label>
                <div class="layui-input-block">
                    <input type="text" name="repairman" lay-verify="required" placeholder="请输入维修人姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">维修日期</label>
                <div class="layui-input-block">
                    <input type="text" name="repairDate" id="repairDate" lay-verify="required" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">处理备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入处理备注" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="processSubmit">确认处理</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelProcess">取消</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 先加载 jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <!-- 再加载 Layui -->
    <script src="~/Scripts/layui/layui.js"></script>
    <script>
    // 确保页面完全加载后再执行
    document.addEventListener('DOMContentLoaded', function() {
        layui.use(['table', 'form', 'layer', 'laydate', 'upload'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var upload = layui.upload;
            var $ = layui.$;

            // 从ViewBag获取管理员状态
            var isAdmin = @(Html.Raw(ViewBag.IsAdminStr ?? "false"));

            console.log('当前用户权限状态 - isAdmin:', isAdmin, '类型:', typeof isAdmin);
            console.log('当前用户权限:', isAdmin ? '管理员' : '普通员工');

            // 将 isAdmin 设置为全局变量，供模板使用
            window.templateIsAdmin = isAdmin;

            // 初始化日期选择器
            laydate.render({
                elem: '#damageDate',
                value: new Date()
            });

            laydate.render({
                elem: '#repairDate',
                value: new Date()
            });

            // 初始化表格
            table.render({
                elem: '#damageRepairTable',
                url: '/DamageRepair/GetDamageRepairList',
                method: 'post',
                toolbar: true,
                title: '明细报损维修记录表',
                cols: [[
                    { type: 'numbers', title: '编号' },
                    { field: 'AssetName', title: '资产名称', width: 150 },
                    { field: 'AssetDetailNum', title: '资产明细编号', width: 150 },
                    { field: 'EmpolyName', title: '申请人', width: 120 },
                    { field: 'DamageDate', title: '损坏时间', width: 120, templet: function(d) {
                        if (!d.DamageDate) return '';
                        // 处理日期格式
                        var dateStr = d.DamageDate.toString();
                        if (dateStr.includes('/Date(')) {
                            return new Date(parseInt(dateStr.replace(/\/Date\((\d+)\)\//, '$1'))).toLocaleDateString();
                        } else {
                            return new Date(dateStr).toLocaleDateString();
                        }
                    }},
                    { field: 'DamageCauses', title: '损坏原因', width: 150 },
                    { field: 'ProblemDescription', title: '问题描述', width: 150 },
                    { field: 'RecordState', title: '维修状态', width: 100, templet: function(d) {
                        return d.RecordState == 1 ? '<span class="layui-badge layui-bg-green">已处理</span>' : '<span class="layui-badge layui-bg-orange">申报中</span>';
                    }},
                    { field: 'DamageRecordReMark', title: '备注', width: 200 },
                    { fixed: 'right', title: '操作', width: isAdmin ? 150 : 100, align: 'center', toolbar: '#barDemo' }
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                parseData: function(res) {
                    console.log('表格数据响应:', res);
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                }
            });

            // 监听工具条
            table.on('tool(damageRepairTable)', function (obj) {
                var data = obj.data;
                console.log('工具条事件:', obj.event, '数据:', data);

                if (obj.event === 'detail') {
                    // 查看详情
                    showDetail(data.DamageRecordID);
                } else if (obj.event === 'process') {
                    // 处理维修 - 只有管理员才能执行
                    if (!isAdmin) {
                        layer.msg('没有权限执行此操作');
                        return;
                    }
                    processRepair(data.DamageRecordID);
                }
            });

            // 搜索按钮事件
            $('#searchBtn').on('click', function () {
                // 获取表单数据
                var formData = $('#searchForm').serializeArray();
                var searchParams = {};

                // 转换为对象格式
                $.each(formData, function () {
                    if (this.value !== '') {
                        searchParams[this.name] = this.value;
                    }
                });

                console.log('搜索参数:', searchParams);

                // 重新加载表格数据
                table.reload('damageRepairTable', {
                    where: searchParams,
                    page: {
                        curr: 1
                    }
                });
            });

            // 重置按钮事件
            $('#resetBtn').on('click', function () {
                // 清空表单
                $('#searchForm')[0].reset();
                form.render();

                // 重新加载表格
                table.reload('damageRepairTable', {
                    where: {},
                    page: {
                        curr: 1
                    }
                });
            });

            // 申请报修按钮事件（普通员工）
            $('#applyRepairBtn').on('click', function () {
                // 加载当前用户正在使用的资产
                $.post('/DamageRepair/GetCurrentUserAssets', function (res) {
                    if (res.code === 0) {
                        var html = '<option value="">请选择资产</option>';
                        $.each(res.data, function (i, item) {
                            html += '<option value="' + item.AssetDetailID + '">' + item.AssetDetailNum + ' - ' + item.AssetName + '</option>';
                        });
                        $('select[name="assetDetailID"]').html(html);
                        form.render('select');
                    } else {
                        layer.msg(res.msg);
                    }
                });

                layer.open({
                    type: 1,
                    title: '申请报修',
                    area: ['600px', '600px'],
                    content: $('#applyRepairForm')
                });
            });

            // 文件上传
            upload.render({
                elem: '.layui-upload-file',
                auto: false,
                choose: function(obj) {
                    // 预览本地图片
                    obj.preview(function(index, file, result){
                        $('#previewImage').attr('src', result).show();
                        $('#uploadText').text(file.name);
                    });
                }
            });

            // 报修表单提交
            form.on('submit(repairSubmit)', function (data) {
                var formData = data.field;
                // 移除图片字段，因为需要单独处理文件上传
                delete formData.problemImage;

                $.post('/DamageRepair/ApplyRepair', formData, function (res) {
                    if (res.code === 0) {
                        layer.msg('报修申请提交成功');
                        layer.closeAll();
                        table.reload('damageRepairTable');
                    } else {
                        layer.msg(res.msg);
                    }
                });
                return false;
            });

            // 查看详情
            function showDetail(damageRecordID) {
                $.post('/DamageRepair/GetDamageDetail', { damageRecordID: damageRecordID }, function (res) {
                    if (res.code === 0) {
                        var data = res.data;
                        $('#detailAssetName').text(data.AssetName || 'null');
                        $('#detailDamageCauses').text(data.DamageCauses);
                        $('#detailProblemDescription').text(data.ProblemDescription);
                        $('#detailEmpolyName').text(data.EmpolyName);

                        // 处理日期显示
                        var damageDate = data.DamageDate ? new Date(parseInt(data.DamageDate.replace(/\D/gi, ""))).toLocaleDateString() : '';
                        $('#detailDamageDate').text(damageDate);

                        $('#detailRepairman').text(data.Repairman || '待处理');

                        var repairDate = data.RepairDates ? new Date(parseInt(data.RepairDates.replace(/\D/gi, ""))).toLocaleDateString() : '待处理';
                        $('#detailRepairDates').text(repairDate);

                        $('#detailRecordState').text(data.RecordState == 1 ? '已处理' : '申报中');
                        $('#detailRemark').text(data.DamageRecordReMark || '暂无');

                        // 处理图片显示
                        if (data.ProblemImage) {
                            $('#detailImage').attr('src', data.ProblemImage).show();
                            $('#noImageText').hide();
                        } else {
                            $('#detailImage').hide();
                            $('#noImageText').show();
                        }

                        layer.open({
                            type: 1,
                            title: '查看详情',
                            area: ['500px', '600px'],
                            content: $('#detailForm'),
                            btn: ['关闭'],
                            yes: function(index) {
                                layer.close(index);
                            }
                        });
                    } else {
                        layer.msg(res.msg);
                    }
                });
            }

            // 处理维修（管理员）
            function processRepair(damageRecordID) {
                $('input[name="damageRecordID"]').val(damageRecordID);

                layer.open({
                    type: 1,
                    title: '处理维修',
                    area: ['400px', '350px'],
                    content: $('#processRepairForm')
                });
            }

            // 处理维修表单提交
            form.on('submit(processSubmit)', function (data) {
                $.post('/DamageRepair/ProcessRepair', data.field, function (res) {
                    if (res.code === 0) {
                        layer.msg('维修处理完成');
                        layer.closeAll();
                        table.reload('damageRepairTable');
                    } else {
                        layer.msg(res.msg);
                    }
                });
                return false;
            });

            // 取消处理
            $('#cancelProcess').on('click', function () {
                layer.closeAll();
            });
        });
    });
    </script>

    <!-- 表格操作列模板 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail">详情</a>
        {{# if(d.RecordState == 0 && window.templateIsAdmin){ }}
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="process">维修</a>
        {{# } }}
    </script>
</body>
</html>